package com.trainoo.payment.mock.util;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p> add description here </p>
 *
 * @author tao.zhou
 * @version 1.0
 * @date 2020/9/14 10:53:00
 */
public class HttpUtil {

    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

    public static final String CHARSET_UTF8 = "UTF-8";

    public static String post(String reqUrl, List<NameValuePair> paramXml) {
        log.info("postUrl: {}, paramString: \n{}", reqUrl, paramXml);
        HttpPost httpPost = new HttpPost(reqUrl);

        try {
            UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(paramXml, "UTF-8");
            httpPost.setEntity(encodedFormEntity);
            CloseableHttpClient client = HttpClients.createDefault();
            CloseableHttpResponse response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                byte[] byteArray = EntityUtils.toByteArray(response.getEntity());
                return IOUtils.toString(byteArray, CHARSET_UTF8);
            } else {
                log.error("操作失败");
            }
        } catch (UnsupportedEncodingException e) {
            log.error("http post参数格式化错误！", e);
        } catch (ClientProtocolException e) {
            log.error("ClientProtocolException", e);
        } catch (IOException e) {
            log.error("IOException", e);
        }
        return "failed";
    }
}
